import os
import random
import threading
import time

import pyttsx3
import edge_tts
from playsound import playsound


def IsConnected():
  import requests
  try:
    html = requests.get("http://www.baidu.com", timeout=2)
  except Exception as e:
    print('[warn]no network!', e)
    return False
  return True


# inConnected = IsConnected()
inConnected = False


def _EdgeSay(text):
  mp3Path = 'temp/{}.mp3'.format(text)
  if os.path.exists(mp3Path):
    playsound(mp3Path)
    return
  import asyncio

  async def Do():
    await t.save(mp3Path)
    playsound(mp3Path)
    # os.remove(mp3Path)

  t = edge_tts.Communicate(text=text, voice='zh-CN-XiaoxiaoNeural', rate='+25%', volume='+0%')
  asyncio.run(Do())


class Speaker:
  def __init__(self):
    # self.engine = pyttsx3.init()
    # self.engine.setProperty('rate', 300)
    self.questList = []
    self.speakThread = threading.Thread(target=self._Main, daemon=True)
    self.speakThread.start()

  def _Main(self):
    while True:
      if self.questList:
        sayText = self.questList[0]
        self.questList.pop(0)
        if inConnected:
          _EdgeSay(sayText.replace(' ', ''))
        else:
          engine = pyttsx3.init()
          engine.setProperty('rate', 300)
          engine.say(sayText)
          engine.runAndWait()
          print('下一句')
          engine.stop()
          del engine
        # self.questList.pop(0)

  def Say(self, text):
    self.questList.append(text)


if __name__ == '__main__':
  s = Speaker()
  s.Say('你好！世界！')
  time.sleep(10)
